package com.winit.issue.manager;

import com.winit.common.CloudLinkSend.MqMsgType;
import com.winit.common.CloudLinkSend.MsgSend;
import com.winit.common.base.bean.ExecuteResult;
import com.winit.issue.common.SequenceUtil;
import com.winit.issue.mapper.IssueMapper;
import com.winit.issue.model.Issue;
import com.winit.issue.model.IssueRelation;
import com.winit.issue.model.IssueStatus;
import com.winit.issue.repository.IssueRelationRepository;
import com.winit.issue.repository.IssueRepository;
import com.winit.issue.repository.IssueRepositoryExt;
import com.winit.need.mapper.NeedMapper;
import com.winit.need.model.Need;
import com.winit.requirement.model.BrdRequirement;
import com.winit.requirement.service.IBrdRequirementService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.*;

@Component
public class IssueManager {

    private static Logger log = LoggerFactory.getLogger(IssueManager.class);

    @Autowired
    private IssueRepository issueRepository;
    @Autowired
    private IssueRepositoryExt issueRepositoryExt;
    @Autowired
    private IBrdRequirementService brdRequirementService;
    @Autowired
    private IssueRelationRepository issueRelationRepository;
    @Autowired
    MsgSend msgSend;

    @Autowired
    private IssueMapper issueMapper;

    @Autowired
    NeedMapper needMapper;
    public List<Issue> saveIssues(List<Issue> issues){
        List<Issue> rs = new ArrayList<>();
        for (Issue issue : issues){
            if (StringUtils.isEmpty(issue.getId())) {
                rs.add(this.createIssue(issue).getData());
            }else{
                rs.add(this.updateIssue(issue).getData());
            }
        }
        return rs;
    }

    public ExecuteResult<Issue> createIssue(Issue issue){
        ExecuteResult<Issue> executeResult = new ExecuteResult();
        issue.setId(SequenceUtil.getIssueId());
        if (StringUtils.isEmpty(issue.getNumber())){
            issue.setNumber(SequenceUtil.getIssueNumber());
        }
        if (null == issue.getCreateTime()){
            issue.setCreateTime(new Date());
        }
        if (null == issue.getUpdateTime()){
            issue.setUpdateTime(new Date());
        }
        if (StringUtils.isEmpty(issue.getContent())){
            String content = "";
            content = StringUtils.isEmpty(issue.getUser()) ? content : issue.getUser();
            content = StringUtils.isEmpty(issue.getAction()) ? content : content + issue.getAction();
            if (!StringUtils.isEmpty(content)){
                issue.setContent(content);
            }
        }
        issue.setStatus(IssueStatus.IN_HAND);
        this.issueRepository.save(issue);
        executeResult.setData(issue);
        return executeResult;
    }

    public ExecuteResult<Issue> updateIssue(Issue issue){
        ExecuteResult<Issue> executeResult = new ExecuteResult();
        Issue dbIssue = this.issueRepository.findOne(issue.getId());
        if (null == dbIssue){
            executeResult.toError("指定的issue不存在");
            return executeResult;
        }
        issue.setUpdateTime(new Date());

        String content = "";
        String user = issue.getUser();
        String action = issue.getAction();
        user = user == null ? dbIssue.getUser() : user;
        action = action == null ? dbIssue.getAction() : action;
        content = StringUtils.isEmpty(user) ? content : user;
        content = StringUtils.isEmpty(action) ? content : content + action;
        issue.setContent(content);
        this.issueRepositoryExt.updateByPropertyNotNull(issue);
        if(!"INHAND".equals(issue.getStatus())){
            this.sendNeed(issue);
        }

        executeResult.setData(issue);
        return executeResult;
    }

    //发送修改need状态消息
    private void sendNeed(Issue issue){
        Issue newIssue = issueRepository.findOne(issue.getId());
        if(StringUtils.isEmpty(newIssue.getNeedId())){
            return;
        }
        Map map=new HashMap<>();
        map.put("needId",newIssue.getNeedId());
        MqMsgType msgType = null;
        switch (issue.getStatus()){
            case "PRD":
                msgType=MqMsgType.PRD;
                break;
            case "ISSUE_DEV":
                msgType=MqMsgType.ISSUE_DEV;
                break;
        }
        if(msgType!=null){
            msgSend.sendIssueMsg(msgType,map);
        }
    }


    public List<Issue> getIssues(String issueId, String type, String creatorAccount, String toAccount, String keyword, String withComplete,Long startDate){
        String statusExclue = null;
        if ("0".equals(withComplete))
            statusExclue = IssueStatus.COMPLETE;
        Issue searchCondition = new Issue();
        searchCondition.setId(issueId);
        searchCondition.setType(type);
        searchCondition.setCreatorAccount(creatorAccount);
        searchCondition.setToAccount(toAccount);

//        searchCondition.setKeyword(keyword);
//        searchCondition.setStatusExclue(statusExclue);
//        return issueMapper.selectByCondition(searchCondition);

        return this.issueRepositoryExt.searchByConditition(searchCondition, statusExclue, keyword, true,startDate);
    }


    public List<Issue> getReqIssues(String reqId){
        List<String> reqIds = new ArrayList<>();
        reqIds.add(reqId);
        BrdRequirement requirement = this.brdRequirementService.searchBrdRequirementsByReqIds(reqIds).get(0);
        String issues = requirement.getIssues();
        if (StringUtils.isEmpty(issues)){
            return null;
        }
        List<String> issueIds = Arrays.asList(issues.split(","));
        return this.issueRepository.findByIdIn(issueIds, issues);
    }


    public ExecuteResult deleteIssue(String issueId){
        ExecuteResult executeResult = new ExecuteResult();
        Issue dbIssue = this.issueRepository.findOne(issueId);
        if (null == dbIssue){
            return executeResult;
        }
        List<IssueRelation> issueRelations = this.issueRelationRepository.findByIssueId(issueId);
        if (!CollectionUtils.isEmpty(issueRelations)) {
            for (IssueRelation issueRelation : issueRelations) {
                if ("REQ".equalsIgnoreCase(issueRelation.getType())) {
                    List<String> reqIds = new ArrayList<>();
                    reqIds.add(issueRelation.getRelationId());
                    BrdRequirement brdRequirement = this.brdRequirementService.searchBrdRequirementsByReqIds(reqIds).get(0);
                    if (null == brdRequirement) {
                        continue;
                    }

                    BrdRequirement update = new BrdRequirement();
                    update.setReqId(brdRequirement.getReqId());
                    String issues = brdRequirement.getIssues();
                    List<String> issueIds = new ArrayList<>();
                    issueIds.addAll(Arrays.asList(issues.split(",")));
                    issueIds.remove(issueId);
                    update.setIssues(BrdRequirement.getIssuesByList(issueIds));
                    this.brdRequirementService.updateBrdById(update);
                    this.issueRelationRepository.delete(issueRelation);
                } else {
                    log.error("目前不支持删除时处理prd与issue的关系");
                }
            }
        }
        this.issueRepository.delete(issueId);
        return executeResult;
    }

    public List<Issue> findByNeedId(String needId){
        List<Issue> issues =this.issueRepository.findByNeedId(needId);
        if(issues.size() > 0){
            for (Issue issue:issues){
                issue.setReqCount(this.issueRelationRepository.countIssueReq(issue.getId()));
            }
        }
        return issues;
    }

}
